package com.wswy.wzcx.module.base

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.content.Context
import android.content.Intent
import com.che.libcommon.utils.RxBus
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.UserMode
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.module.InternalMsgCode
import io.reactivex.observers.ResourceObserver

open class UserViewModel : BaseViewModel() {

   private val userLiveData = MutableLiveData<UserMode?>()

    override fun onCreate() {
        super.onCreate()

        userLiveData.postValue(DataCenter.get()?.userMode)
    }

    open fun registerObservers() {


        val userLoginObserver = object : ResourceObserver<UserMode>() {
            override fun onNext(userMode: UserMode) {

                onUserLoginSuccess(userMode)
            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        }

        val userLogoutObserver = object : ResourceObserver<UserMode>() {
            override fun onNext(userMode: UserMode) {
                onLogout()
            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        }


        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGIN_SUCCESS, UserMode::class.java)
                .subscribe(userLoginObserver)

        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGOUT, UserMode::class.java)
                .subscribe(userLogoutObserver)

        addRun(userLoginObserver)
        addRun(userLogoutObserver)
    }


    open fun onUserLoginSuccess(userMode: UserMode?) {

        userLiveData.postValue(userMode)

    }

    open fun onLogout() {
        userLiveData.postValue(null)
    }


    fun getUserLiveData():LiveData<UserMode?> = userLiveData

    fun hasLogin(): Boolean {
        return DataCenter.get().hasLogin()
    }

    fun gotoLogin(context: Context) {
        context.startActivity(RouterUtils.getLogin())

    }

}